from channels.generic.websocket import WebsocketConsumer
import json
from api import models
# 同步执行
from asgiref.sync import async_to_sync

user_list = []


class ChatConsumer(WebsocketConsumer):
    def connect(self):
        self.room_name = 'chatRoom'
        # 名字随意取
        self.room_group_name = 'dweb'

        # 添加通道层
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )
        # 通过(返回)
        self.accept()

    def disconnect(self, close_code):
        # 离开时调用退出通道层
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )

    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        # message = text_data_json['message']
        # 获取用户token和code状态
        message = chat_code_to_msg(text_data_json['code'], text_data_json['msg'])
        # 表示自定义的函数和值
        event = {
            'type': 'chat_message',
            'message': message
        }
        # 同步发送消息
        async_to_sync(self.channel_layer.group_send)(self.room_group_name, event)
        # self.send(text_data=json.dumps({
        #     'message': message
        # }))

    def chat_message(self, event):
        message = event['message']
        self.send(text_data=json.dumps(message))


# 消息发送
def chat_code_to_msg(code, msg):
    global user_list
    if code == 100:
        user_object = models.UserInfo.objects.filter(token=msg).first()
        user_item = {
            'id': user_object.id,
            'username': user_object.nickname
        }
        if user_item not in user_list:
            user_list.append(user_item)

        res = {
            'code': 100,
            'userlist': user_list
        }
        print(res)
        return res
    if code == 888:
        user_object = models.UserInfo.objects.filter(token=msg).first()
        user_item = {
            'id': user_object.id,
            'username': user_object.nickname
        }
        if user_item in user_list:
            user_list.remove(user_item)

        res = {
            'code': 888,
            'userlist': user_list
        }
        print(res)
        return res
    if code == 200:
        user_object = models.UserInfo.objects.filter(token=msg['token']).first()
        res = {
            'code': 200,
            'msg': {
                'id': user_object.id,
                'username': user_object.nickname,
                'avatar': user_object.avatar,
                'text': msg['text']
            }
        }
        return res
